﻿using System.Configuration;
using System.Linq;
using System.Web.UI.WebControls;
using Controllers;

namespace Web
{
    public partial class RoleEmp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {
            ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            string strSql = @"with t as (select Id,Pid,cast(Text as nvarchar(500)) Text,OrderNo,1 lvl,cast(OrderNo as nvarchar(50)) orderStr,IsValid from Depts where Pid is null
union all
select d.Id,d.Pid,cast(REPLICATE('--',t.lvl)+d.Text as nvarchar(500)),
d.OrderNo,t.lvl+1,cast(t.orderStr+cast(d.OrderNo as nvarchar(50)) as nvarchar(50)),d.IsValid
from Depts d,t where d.Pid=t.id
)
  select Id,Text from t where IsValid=1 order by orderStr;";
            var depts = ctx.ExecuteQuery<DeptDTO>(strSql);
            Dept.DataSource = depts;
            Dept.DataValueField = "Id";
            Dept.DataTextField = "Text";
            Dept.DataBind();
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            int deptId = ebi.EmpDepPos.First().DeptId;
            Dept.Value = deptId.ToString();

            var positions = from r in ctx.Positions select new { r.Id, r.Name };
            Position.DataSource = positions;
            Position.DataValueField = "Id";
            Position.DataTextField = "Name";
            Position.DataBind();
            Position.Items.Insert(0, new ListItem("", ""));

            int roleId = int.Parse(Request.QueryString["roleId"]);
            //未授权人员
            strSql = @"with t as(select Id,Text from Depts where Id={0}
  union all
  select a.Id,a.Text from Depts a,t where a.IsValid=1 and a.Pid=t.Id)
select Id,Name from(SELECT a.Id,Name,MIN(b.PosId)PosId FROM Employee a,EmpDepPositions b
  where LeaveDate is null
  and a.Id in(select EmpId from EmpDepPositions where DeptId in(select Id from t))
  and a.Id not in(SELECT EmpId FROM EmpRoles where RoleId={1})
  and a.Id=b.EmpId group by a.Id,Name)t2 order by PosId;";
            var list = ctx.ExecuteQuery<EmpBasicInfo>(strSql, deptId, roleId);
            rptEmployeeList.DataSource = list;
            rptEmployeeList.DataBind();
            //已授权人员
            strSql = @"SELECT Id,Name FROM Employee
  where LeaveDate is null and Id in(SELECT EmpId
  FROM EmpRoles where RoleId={0});";
            var list0 = ctx.ExecuteQuery<EmpBasicInfo>(strSql, roleId);
            rptChoosedEmployeeList.DataSource = list0;
            rptChoosedEmployeeList.DataBind();
        }
    }
}